package com.wu.leetcode.leetcode47;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Leetcode47-全排列 II
 *
 * @author lynn
 * @date 2020/8/17 - 20:21
 */
class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return null;
        }
        Arrays.sort(nums);
        dfs(nums, new boolean[nums.length], res, new ArrayList<Integer>());
        return res;
    }

    private void dfs(int[] nums, boolean[] visited, List<List<Integer>> res, ArrayList<Integer> list) {
        if (nums.length == list.size()) {
            res.add(new ArrayList<>(list));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (visited[i]) {
                continue;
            }
            //visited[i - 1] 一开始还是会添加在结果里面
            if (i > 0 && nums[i] == nums[i - 1] && !visited[i - 1]) {
                continue;
            }
            list.add(nums[i]);
            visited[i] = true;
            dfs(nums, visited, res, list);
            visited[i] = false;
            list.remove(list.size() - 1);
        }
    }
}
